package com.jzo2o.orders.manager.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.manager.service.IOrdersCanceledService;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 订单取消监听
 */
@Component
@Slf4j
public class OrderCancelListener {

    @Resource
    private IOrdersCanceledService ordersCanceledService;
    @Resource
    private IOrdersCreateService ordersCreateService;

    /**
     * 延时队列
     *
     * @param ordersId 订单取消信息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "order.cancel.queue", durable = "true"),
            exchange = @Exchange(value = "jzo2o.delay.exchange", delayed = "true"),
            key = "cancel"
    ))
    public void cancelOrder(String ordersId) {
        log.info("订单取消监听{}", ordersId);
        Long orderId = Long.parseLong(ordersId);
        //检测订单状态
        Orders orders = ordersCreateService.getOne(Wrappers.<Orders>lambdaQuery()
                .eq(Orders::getId, orderId)
                .eq(Orders::getPayStatus, OrderStatusEnum.NO_PAY.getStatus()));
        if (orders == null) {
            log.info("已经支付或取消");
            return;
        }
        //未支付订单取消
        orders.setOrdersStatus(OrderStatusEnum.CANCELED.getStatus());
        orders.setCancelReason("订单超时");
        //订单取消
        ordersCreateService.updateById(orders);
        ordersCanceledService.CancelOrderByMq(orders.getId());
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.Queues.ORDERS_REFUND_SUCCESS, durable = "true"),
            exchange = @Exchange(value = MqConstants.Exchanges.TRADE),
            key = MqConstants.RoutingKeys.REFUND
    ))
    public void refundSuccess(String refundInfo) {
        log.info("退款成功监听{}", refundInfo);
        ordersCanceledService.refundSuccess(refundInfo);
    }

}
